/**
 * Meituan.com Inc.
 * Copyright (c) 2010-2019 All Rights Reserved.
 */
package cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import second.User;

import java.lang.reflect.Method;

/**
 * cglib动态代理示例
 *
 * @author tuyou@meituan.com
 * @version v0.1 2019-03-03 8:27 PM tuyou Exp $$
 */
public class CglibProxy implements MethodInterceptor {

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(target.getClass());
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("intercept before....");
        Object obj = method.invoke(target, objects);
        System.out.println("intercept after....");
        return obj;
    }

    public static void main(String[] args) {
        User user = (User)new CglibProxy().getInstance(new User());
        user.save("tuyou", 25);
    }
}